package com.kung.qvs.ui.main.fragment;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.kung.qvs.BR;
import com.kung.qvs.R;
import com.kung.qvs.data.JtRepository;
import com.kung.qvs.entity.PrintDataBean;
import com.kung.qvs.entity.SupplierBean;
import com.kung.qvs.entity.database.SqlManager;

import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class SupplierManageViewModel extends BaseViewModel<JtRepository> {
    public SupplierManageViewModel(@NonNull Application application, JtRepository model) {
        super(application, model);
    }

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        public SingleLiveEvent eventToBackPage = new SingleLiveEvent<>();
        public SingleLiveEvent<SupplierBean> eventToAddPage = new SingleLiveEvent<>();
    }

    private List<SupplierBean> supplierBeanList = new ArrayList<>();
    //给RecyclerView添加ObservableList
    public ObservableList<SupplierManageItemModel> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<SupplierManageItemModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_supplier_record);

    public BindingCommand onCommandBack = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventToBackPage.call();
        }
    });

    //新增
    public BindingCommand onCommandAdd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventToAddPage.call();
        }
    });

    @Override
    public void onResume() {
        super.onResume();
        doGetDataBeans();
    }

    private void doGetDataBeans(){
        supplierBeanList = SqlManager.querySupplierBeans(); //查询全部
        //清除列表
        observableList.clear();
        if (supplierBeanList != null && supplierBeanList.size() > 0) {
            for(int i = 0; i < supplierBeanList.size(); i++) {
                supplierBeanList.get(i).setIndex((i + 1) + "");
                observableList.add(new SupplierManageItemModel(SupplierManageViewModel.this, supplierBeanList.get(i)));
            }
        }
    }

    public void doDeleteDataBean(SupplierBean bean) {
        SqlManager.deleteSupplierBeanById(bean.get_id());
        doGetDataBeans();
    }
}
